package cn.wolfcode.p2p.base.interceptor;

import cn.wolfcode.p2p.base.anno.NeedLogin;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截检查
 */
@Component
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前请求的资源是一个方法,才做登录判断
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            //判断方法上是否贴有@NeedLogin标签
            boolean isNeedLogin = method.hasMethodAnnotation(NeedLogin.class);
            //如果有标签,再判断session中是否有登录对象
            if (isNeedLogin && UserContext.getLoginInfo() == null) {
                response.sendRedirect("/login.html");
                return false;
            }
        }
        //如果没有标签,方法
        //其他放行
        return true;
    }
}
